
// 自定义请求方式的类型
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'

// 请求配置的类型 ?表示可选, Record<string, any> 键是字符串，值是任意类型
interface sendConfig {
  url: string
  method: RequestMethod
  header?: any
  data?: Record<string, any>
  params?: Record<string, any>
  loadingStatus?: boolean,
  auth?: boolean
  loading?: boolean,
}
// 详情参数配置类型
export interface responseConfig<T = any> {
  code: number | string
  msg?: string
  message?: string
  data?: T
}

// 封装发送请求的方法
const server = <T>(config: sendConfig) => {
    // 此判断是将GET请求的参数拼接到URL上
    if (config.method === 'GET' && config.params) {
        let url = config.url + '?'
        for (const keyName of Object.keys(config.params)) {
          const value = config.params[keyName]
          const part = encodeURIComponent(keyName) + '='
          if (value !== null && typeof value !== 'undefined') {
            if (typeof value === 'object') {
              for (const key of Object.keys(value)) {
                const params = keyName + '[' + key + ']'
                const subPart = encodeURIComponent(params) + '='
                url += subPart + encodeURIComponent(value[key]) + '&'
              }
            } else {
              url += part + encodeURIComponent(value) + '&'
            }
          }
        }
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }
    // 从环境变量读取当前请求域名
    const Url = import.meta.env.VITE_API_URL as string
    console.log(Url)
    const token = uni.getStorageSync('token')
    // 添加自定义请求头
    if (config.header) {
        config.header.token = 'token ' + token
    } else {
        config.header = {
            token: 'token2222 ' + token,
        }
    }
    return new Promise<responseConfig<T>>((reslove, reject) => {
        if(!token && config.auth){
          return reject("请登录")
        }
        if (!config.loading) {
          uni.showLoading({
            title: '加载中...',
            mask: true,
          })
        }
        uni.request({
            url: Url + config.url,
            method: config.method || 'GET',
            header: config.header,
            data: config.data || {},
            success: (res: any) => {
              console.log('res', res)
              if (!config.loading) {
                uni.hideLoading()
              }
              if (res.statusCode == 200) {
                reslove(res.data)
              } else if (res.data.code != 401) {
                reject(res)
              }
            },
            fail: (res: any) => {
              if (!config.loading) {
                uni.hideLoading()
              }
              if (res.msg && res.msg.indexOf('timeout') !== -1) {
                console.log('请求超时，请稍后再试')
              } else if (res.msg && res.msg.indexOf('request') !== -1) {
                console.log('服务器已关闭')
              } else {
                console.log('请求失败，请检查网络')
                uni.$u.toast('请求失败，请检查网络')
              }
              reject('请求失败')
            }
          })
    })
}

export default server